<template>
  <view class="container">
    <!-- 顶部个人信息卡片 -->
    <view class="profile-card">
      <view class="profile-avatar">
        <u-upload
          class="avatar-upload"
          :fileList="fileList1"
          @afterRead="afterRead"
          @delete="deletePic"
          name="1"
          :maxCount="1"
        >
          <view class="avatar-placeholder">
            <u-icon name="camera" size="40" color="#fff"></u-icon>
          </view>
        </u-upload>
      </view>

      <view class="profile-info" @click="openDatePicker">
        <text class="profile-name" @click="openDatePicker">{{ info.compellation || "陈欢欢" }}</text>
        <view class="profile-details">
          <view class="detail-item">
            <text class="detail-label">性别</text>
            <text class="detail-value">{{info.sex == 1 ? "男" : "女" }}</text>
          </view>
          <!-- <view class="detail-item">
            <text class="detail-label">年龄</text>
            <text class="detail-value">{{ "18" || "--" }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">身高</text>
            <text class="detail-value">{{ "180" || "--" }}cm</text>
          </view> -->
        </view>
        <view class="date-picker" @click="openDatePicker">
          <text class="date-label">体测日期</text>
          <text class="date-value" @click="openDatePicker">
            {{ formData.recordDate || "请选择日期" }}
          </text>
        </view>
      </view>
    </view>

    <!-- 照片上传区域 -->
    <view class="photo-section">
      <view class="section-header">
        <view class="section-title">身体照片记录</view>
      </view>

      <view class="photo-grid">
        <view
          class="photo-item"
          v-for="(item, index) in photoTypes"
          :key="index"
        >
          <u-upload
            class="photo-upload"
            :fileList="getFileList(item.field)"
            @afterRead="(event) => afterRead(event, item.field)"
            @delete="(event) => deletePic(event, item.field)"
            :name="item.field"
            :maxCount="1"
          >
            <template v-if="!formData[item.field]">
              <view class="upload-card">
                <view class="upload-content">
                  <u-icon name="camera-fill" color="#666" size="44"></u-icon>
                  <text class="upload-title">{{ item.text }}</text>
                  <text class="upload-desc">点击上传</text>
                </view>
              </view>
            </template>
            <template v-else>
              <view class="preview-image-wrapper">
                <image
                  :src="formData[item.field]"
                  mode="aspectFit" 
                  class="preview-image"
                  style="width: 100%; height: auto;" 
                />
              </view>
            </template>
          </u-upload> 
        </view>
      </view>
    </view>

    <!-- 数据记录区域 -->
    <view class="data-section">
      <view class="section-title">身体数据记录</view>
      <view class="data-grid">
        <view class="data-card" v-for="(item, index) in fitnessItems" :key="index">
          <view class="data-input">
            <u--input
              v-model="formData.fitness[item.field].value"
              placeholder="请输入"
              border="none"
              @change="handleDataChange(item.field, $event)"
            ></u--input>
          </view>
          <text class="data-label">{{ item.label }}</text>
          <text class="data-unit">{{ item.unit }}</text>
        </view>
      </view>
    </view>

    <!-- 新增按钮 -->
    <view class="add-section">
      <button class="add-btn" @click="addFitnessItem">
        <text class="btn-text">新增数据</text>
      </button>
    </view>

    <!-- 保存按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="submit(3)">
        <text class="btn-text">保存数据</text>
      </button>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="show"
      v-model="value1"
      mode="date"
      @close="show = false"
      @cancel="show = false"
      @confirm="confirm"
    ></u-datetime-picker>
  </view>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

import { addfitness, uploadFile,customerDetail } from "../../api/fit";
export default {
  name: "",
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      show: false,
      value1: "", // 记录日期
      formData: {
        customerId: '',
        frontPic: "",
        flankPic: "",
        backPic: "",
        fitness: {
          weight: {
            label: "体重",
            value: ""
          },
          fat: {
            label: "体脂率",
            value: ""
          },
          bmi: {
            label: "BMI",
            value: ""
          },
          metabolism: {
            label: "基础代谢",
            value: ""
          },
          slm: {
            label: "肌肉量",
            value: ""
          },
          whr: {
            label: "腰臀比",
            value: ""
          },
          bust: {
            label: "胸围",
            value: ""
          },
          waist: {
            label: "腰围",
            value: ""
          },
          hipline: {
            label: "臀围",
            value: ""
          }
        },
        recordDate: "",
      },
      // 照片类型定义
      photoTypes: [
        {
          text: "正面照片",
          field: "frontPic",
          desc: "正面站姿",
          icon: "camera",
        },
        {
          text: "侧面照片",
          field: "flankPic",
          desc: "侧面站姿",
          icon: "camera",
        },
        {
          text: "背面照片",
          field: "backPic",
          desc: "背面站姿",
          icon: "camera",
        },
      ],
      // 身体数据项定义
      fitnessItems: [
        { label: "体重", field: "weight", unit: "kg" },
        { label: "体脂率", field: "fat", unit: "%" },
        { label: "BMI", field: "bmi", unit: "" },
        { label: "基础代谢", field: "metabolism", unit: "kcal" },
        { label: "肌肉量", field: "slm", unit: "kg" },
        { label: "腰臀比", field: "whr", unit: "" },
        { label: "胸围", field: "bust", unit: "cm" },
        { label: "腰围", field: "waist", unit: "cm" },
        { label: "臀围", field: "hipline", unit: "cm" },
      ],
      info:{},
    };
  },
  created() {},
  mounted() {},
  onLoad(e) {
    this.formData.customerId = e.id;
    this.getInfo()
  },
  methods: {
    async getInfo(){
      const res = await customerDetail(this.formData.customerId);
      this.info = res.data;
    },
    openDatePicker() {
      this.show = true;
    },

    // 确认日期选择
    confirmDate(e) {
      // 格式化日期
      const date = new Date(e);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      this.formData.recordDate = `${year}-${month}-${day}`;
      this.show = false;
    },

    // 取消日期选择
    cancelDate() {
      this.show = false;
    },
    // 处理日期选择确认
    async confirm(e) {
      const timeFormat = uni.$u.timeFormat;
      this.value1 = timeFormat(e.value, "yyyy-mm-dd");
      this.formData.recordDate = this.value1;
      this.show = false;
    },

    // 处理数据输入变化
    handleDataChange(field, value) {
      this.formData.fitness[field].value = value;
    },

    // 处理图片上传
    afterRead(event) {
      const { file, name } = event;
      // 根据 name 找到对应的照片类型
      const photoType = this.photoTypes.find((item) => item.field === name);
      if (photoType) {
        // 这里可以处理图片上传逻辑，上传成功后设置对应的 URL
        this.formData[photoType.field] = file.url;
      }
    },

    // 删除图片
    deletePic(event) {
      const { name } = event;
      const photoType = this.photoTypes.find((item) => item.field === name);
      if (photoType) {
        this.formData[photoType.field] = "";
      }
    },
    // 获取每个上传组件的文件列表
    getFileList(field) {
      return this.formData[field]
        ? [
            {
              url: this.formData[field],
            },
          ]
        : [];
    },

    // 处理图片上传
    async afterRead(event, field) {
      const { file } = event;
      try {
        uni.showLoading({
          title: "上传中..."
        });
        // 直接传入文件路径
        const res = await uploadFile(file.url);
        if (res.code === 200) {
          this.formData[field] = 'https://api.itaster.cn/file/' + res.message; // 设置返回的图片URL，并拼接前缀
          uni.showToast({
            title: "上传成功",
            icon: "success"
          });
        } else {
          throw new Error(res.msg || "上传失败");
        }
        
      } catch (error) {
        console.error("上传错误:", error);
        uni.showToast({
          title: "上传失败",
          icon: "none"
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 删除图片
    deletePic(event, field) {
      this.formData[field] = "";
    },

    // 新增身体数据项
    addFitnessItem() {
      uni.showModal({
        title: '新增数据项',
        content: '',
        editable: true,
        success: (res) => {
          if (res.confirm) {
            const newItemLabel = res.content;
            if (newItemLabel) {
              uni.showModal({
                title: '输入单位',
                content: '',
                editable: true,
                success: (unitRes) => {
                  if (unitRes.confirm) {
                    const newItemUnit = unitRes.content;
                    const newItemField = this.convertToPinyin(newItemLabel);
                    this.$set(this.formData.fitness, newItemField, { label: newItemLabel, value: "" });
                    this.fitnessItems.push({ label: newItemLabel, field: newItemField, unit: newItemUnit });
                  }
                }
              });
            }
          }
        }
      });
    },

    // 汉字转拼音的方法
    convertToPinyin(chinese) {
      const pinyinMap = {
        "体重": "weight",
        "体脂率": "fat",
        "BMI": "bmi",
        "基础代谢": "metabolism",
        "肌肉量": "slm",
        "腰臀比": "whr",
        "胸围": "bust",
        "腰围": "waist",
        "臀围": "hipline"
      };
      return pinyinMap[chinese] || chinese.split('').map(char => char.charCodeAt(0).toString(36)).join('');
    },

    // 提交表单
    async submit() {
      // console.log(this.formData);
      // return
      
      try {
        // 获取当前日期
        // const currentDate = new Date();
        // const year = currentDate.getFullYear();
        // const month = String(currentDate.getMonth() + 1).padStart(2, "0");
        // const day = String(currentDate.getDate()).padStart(2, "0");
        // this.formData.recordDate = `${year}-${month}-${day}`;
        const res = await addfitness(this.formData);
        if (res.code === 200) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        uni.showToast({
          title: "保存失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 30rpx;
}

// 个人信息卡片
.profile-card {
  position: relative;
  display: flex;
  padding: 40rpx;
  background: #000;
  border-radius: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  margin-bottom: 40rpx;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: linear-gradient(45deg, rgba(255, 255, 255, 0.1), transparent);
  }
}

.profile-avatar {
  width: 180rpx;
  height: 180rpx;
  margin-right: 40rpx;

  .avatar-upload {
    width: 100%;
    height: 100%;
  }

  .avatar-placeholder {
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }
  }
}

.profile-info {
  flex: 1;
  color: #fff;
}

.profile-name {
  font-size: 40rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
}

.profile-details {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 10rpx;

  .detail-label {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }

  .detail-value {
    font-size: 28rpx;
  }
}

.date-picker {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 12rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    background: rgba(255, 255, 255, 0.15);
  }

  .date-label {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }

  .date-value {
    font-size: 28rpx;
  }
}

// 照片上传区域
.photo-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);

  .section-header {
    padding: 0 10rpx;
    margin-bottom: 30rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24rpx;
  padding: 0 10rpx;
}

.photo-item {
  position: relative;
  width: 100%;
  aspect-ratio: 3/4;
  border-radius: 16rpx;
  overflow: hidden;
  background: #f8f8f8;
}

.photo-upload {
  width: 100%;
  height: 100%;

  ::v-deep .u-upload {
    width: 100% !important;
    height: 100% !important;

    &__button {
      width: 100% !important;
      height: 100% !important;
    }

    &__wrap {
      width: 100% !important;
      height: 100% !important;
      margin: 0 !important;
    }

    &__preview-wrap {
      width: 100% !important;
      height: 100% !important;
      margin: 0 !important;
      border-radius: 16rpx;
      overflow: hidden;
    }
  }
}

.upload-card {
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  padding: 20rpx;

  &:active {
    background: #f0f0f0;
  }

  .upload-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
  }

  .upload-title {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    text-align: center;
  }

  .upload-desc {
    font-size: 24rpx;
    color: #999;
    text-align: center;
  }
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 16rpx;
}

// 数据记录区域
.data-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.data-card {
  position: relative;
  padding: 30rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
  }

  .data-input {
    margin-bottom: 16rpx;

    ::v-deep .u-input {
      background: transparent;
      font-size: 32rpx;
      font-weight: 500;
    }
  }

  .data-label {
    font-size: 26rpx;
    color: #666;
  }

  .data-unit {
    position: absolute;
    right: 30rpx;
    bottom: 30rpx;
    font-size: 24rpx;
    color: #999;
  }
}

// 新增按钮
.add-section {
  padding: 20rpx;
}

.add-btn {
  width: 100%;
  height: 90rpx;
  background: #000;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  transform: translateY(0);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  }

  .btn-text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
  }
}

// 提交按钮
.submit-section {
  padding: 20rpx;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background: #000;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  transform: translateY(0);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  }

  .btn-text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
  }
}

// 修复上传组件样式
::v-deep .u-upload {
  &__button {
    width: 100% !important;
    height: 100% !important;
  }

  &__wrap {
    width: 100% !important;
    height: 100% !important;
  }

  &__preview-wrap {
    border-radius: 16rpx;
    overflow: hidden;
  }
}

.profile-card {
  position: relative;
  display: flex;
  padding: 40rpx;
  background: #000;
  border-radius: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  margin-bottom: 40rpx;
  z-index: 1; // 确保卡片在正确的层级
}

.profile-info {
  flex: 1;
  position: relative;
  z-index: 2; // 确保信息在正确的层级
}

// 新增包装器确保点击区域正确
.date-picker-wrapper {
  position: relative;
  z-index: 3;
  margin-top: 20rpx;
}

.date-picker {
  position: relative;
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 12rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  z-index: 3;

  // 移除可能影响点击的属性
  pointer-events: auto;

  &:active {
    opacity: 0.8;
    background: rgba(255, 255, 255, 0.2);
  }
}

.date-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
}

.date-value {
  font-size: 28rpx;
  color: #ffffff;
}

// 确保没有其他元素覆盖
.profile-card::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(45deg, rgba(255, 255, 255, 0.1), transparent);
  z-index: 1;
  pointer-events: none; // 确保不影响点击
}
</style>
